package com.ehotting.edsta.mqbd.monitor.web.controller;

import com.ehotting.eaf.core.DateHelper;
import com.ehotting.eaf.core.web.domain.AjaxResult;
import com.ehotting.edsta.mqbd.api.enums.SysModuleEnum;
import com.ehotting.mqbd.api.bean.solver.SolverInfoBean;
import com.ehotting.mqbd.api.bean.solver.SolverStateBean;
import com.ehotting.mqbd.core.manager.NacosSolverManager;
import com.ehotting.mqbd.core.manager.SolverInfoManager;
import com.fasterxml.jackson.core.JsonProcessingException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PostMapping;
import java.util.Date;

@Controller("/module")
public class ModuleController {

    private static Logger logger = LoggerFactory.getLogger(ModuleController.class);

    @Autowired
    private SolverInfoManager solverInfoManager;

    @Autowired
    private NacosSolverManager nacosSolverManager;

    @PostMapping("/login")
    public Object login(String module,String ip,String port){
        logger.info("Start login.");
        SysModuleEnum sysModule = SysModuleEnum.getByCode(module);
        if(sysModule==null){
            return AjaxResult.error("module is null.");
        }

        logger.info("module[{}],ip[{}],port[{}]",module,ip,port);
        SolverStateBean solverState = new SolverStateBean();
        SolverInfoBean solverInfo = new SolverInfoBean();
        solverInfo.setIp(ip);
        solverInfo.setPort(port);
        solverInfo.setName(sysModule.getName()+":"+ DateHelper.toSeparatorStringyyyyMMddHHmmss(new Date()));
        solverState.setSolverInfo(solverInfo);
        solverState.setAvailable();
        solverState.setSolvingCount(0);
        solverState.setModule(module);
        solverInfoManager.save( solverState);
        try {
            nacosSolverManager.add(module,solverInfo);
        } catch (JsonProcessingException e) {
            logger.error("Module["+module+",ip:"+ip+"] login error",e);
            return AjaxResult.error(e.getMessage());
        }
        return AjaxResult.success();
    }

    @PostMapping("/logout")
    public Object logout(String module,String ip,String port)  {
        logger.info("Start logout.");
        SysModuleEnum sysModule = SysModuleEnum.getByCode(module);
        if(sysModule==null){
            return AjaxResult.error("module is null.");
        }
        logger.info("module[{}],ip[{}],port[{}]",module,ip);
        solverInfoManager.delete(module,ip);

        SolverInfoBean solverInfo = new SolverInfoBean();
        solverInfo.setIp(ip);
        solverInfo.setPort(port);
        try {
            nacosSolverManager.delete(module,solverInfo);
        } catch (JsonProcessingException e) {
            logger.error("Module["+module+",ip:"+ip+"] logout error",e);
            return AjaxResult.error(e.getMessage());
        }
        return AjaxResult.success();
    }


}
